import {
  BadRequestException,
  Injectable,
  ServiceUnavailableException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { AccountService } from '../module/grocery/service/account.service';
import { Account } from '../module/grocery/entities/account.entity';
import { UserService } from 'src/module/custom/service/user.service';
import { User } from 'src/module/custom/entities/user.entity';
import { jwtConstants } from 'src/utils/constant';

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly accountService: AccountService,
    private readonly userService: UserService,
  ) {}

  async validateUser(username: string, pass: string): Promise<any> {
    try {
      const user = await this.accountService.findUser(username);

      if (!user) {
        throw new BadRequestException('用户名不正确！');
      }

      
      if (!bcrypt.compareSync(pass, user.password)) {
        throw new BadRequestException('密码错误！');
      }
      
      return { id: user.id, username: user.username, role: user.role };
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  // 生成 jwt
  async login(user: Account) {
    try {
      const payload = {
        username: user.username,
        userId: user.id,
        role: user.role,
      };

      return {
        access_token: this.jwtService.sign(payload, {
          secret: jwtConstants.secret,
        }),
      };
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  /* custom 校验 */

  async validateCustomUser(username: string, pass: string): Promise<any> {
    const user = await this.userService.findUser(username);

    if (!user) {
      throw new BadRequestException('用户名不正确！');
    }

    if (!bcrypt.compareSync(pass, user.password)) {
      throw new BadRequestException('密码错误！');
    }

    return { userId: user.id, username: user.username, role: user.role };
  }

  // 生成 jwt
  async loginCustom(user: User) {
    const payload = {
      username: user.username,
      userId: user.id,
      role: user.role,
    };

    return {
      access_token: this.jwtService.sign(payload, {
        secret: jwtConstants.secret,
      }),
    };
  }
}
